<template>
  <div
    id="scrollingDiv"
    class="scroll-container"
    style="width: 100%; height: 100%"
  >
    <div class="item">1- 121233fffffr国家认可更健康进口价格困扰</div>
    <div class="item">2- 3123233</div>
    <div class="item">3- 个人口结构俄跨入国际科技馆客人感觉</div>
    <div class="item">4- ggrgerg</div>
    <div class="item">5- fvdgdv</div>
    <div class="item">6- 德国南部巴士与卡车相撞起火</div>
    <div class="item">7- 外交部再次回应印军越界:要求立即将越界部队撤回</div>
    <div class="item">8- 德国网红致信默克尔</div>
    <div class="item">9- 国资委原</div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
let scrollingDiv;
let scrollHeight;
let scrollTop = 0;
let scrollDirection = 1; // 1 表示向下，-1 表示向上
let timer;
const props = defineProps(
  { autoScroll: { type: Boolean, default: true },
  speed:{type:Number,default:0.5}// 滚动速度，可以根据需要调整
 }
);
watch(
  () => props.autoScroll,
  (newValue) => {
    console.log(newValue);
    if (newValue === false) {
      scrollingDiv = null;
      scrollContent();
    } else {
      scrollingDiv = document.getElementById("scrollingDiv");
      scrollHeight = scrollingDiv.scrollHeight;
      scrollContent();
    }
  }
);
watch(
  () => props.speed,
  (newValue) => {
    scrollContent()
  }
);
onMounted(() => {
  scrollingDiv = document.getElementById("scrollingDiv");
  scrollHeight = scrollingDiv.scrollHeight;
  if (props.autoScroll) {
    scrollContent();
  }
});
onUnmounted(() => {
  scrollingDiv = null;
  scrollContent();
});
const scrollContent = () => {
  if (scrollingDiv === null) {
    return;
  }

  if (scrollTop > scrollingDiv.scrollHeight - scrollingDiv.clientHeight) {
    // 滚动到底部，暂停
    scrollTop = scrollingDiv.scrollHeight - scrollingDiv.clientHeight;
    scrollingDiv.scrollTop = scrollTop;
    setTimeout(function () {
      scrollDirection = -1; // 更改滚动方向为向上
      scrollContent(); // 继续滚动
    }, 2000);
  } else if (scrollTop < 0) {
    // 滚动到顶部，暂停
    scrollTop = 0;
    scrollingDiv.scrollTop = scrollTop;
    setTimeout(function () {
      scrollDirection = 1; // 更改滚动方向为向下
      scrollContent(); // 继续滚动
    }, 2000);
  } else {
    // 正常滚动
    scrollTop += scrollDirection * props.speed;
    scrollingDiv.scrollTop = scrollTop;
    // 递归调用以继续滚动
    timer = requestAnimationFrame(scrollContent);
  }
};
</script>
<style lang="less" scoped>
.scroll-container {
  height: 100%; /* 设置你希望的高度 */
  overflow: auto; /* 允许内容溢出时滚动 */
  position: relative; /* 可能需要这个属性以便使用CSS动画或JavaScript进行定位 */
}
</style>